package org.dromara.business.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.business.constant.BusinessConstants;
import org.dromara.business.domain.Audit;
import org.dromara.business.domain.bo.AuditBo;
import org.dromara.business.domain.vo.AuditVo;
import org.dromara.business.mapper.AuditMapper;
import org.dromara.business.service.AuditService;
import org.dromara.business.service.BusinessConfigService;
import org.dromara.business.service.UserFlowingService;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 提现审核Service业务层处理
 *
 * @author zlj
 * @date 2024-07-15
 */
@RequiredArgsConstructor
@Service
public class AuditServiceImpl extends ServiceImpl<AuditMapper, Audit> implements AuditService {

    private final AuditMapper baseMapper;
    private final ISysUserService userService;
    private final BusinessConfigService configService;
    private final UserFlowingService userFlowingService;

    /**
     * 查询提现审核
     */
    @Override
    public AuditVo queryById(Long auditId) {
        return baseMapper.selectVoById(auditId);
    }

    /**
     * 查询提现审核列表
     */
    @Override
    public TableDataInfo<AuditVo> queryPageList(AuditBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Audit> lqw = buildQueryWrapper(bo);
        Page<AuditVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollectionUtil.isNotEmpty(result.getRecords())) {
            BigDecimal auditFee = BigDecimal.ONE.subtract(new BigDecimal(configService.queryValueByKey("audit_fee")));
            for (AuditVo record : result.getRecords()) {
                record.setRelRalance(record.getBalance().multiply(auditFee).setScale(2, RoundingMode.HALF_UP));
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询提现审核列表
     */
    @Override
    public List<AuditVo> queryList(AuditBo bo) {
        LambdaQueryWrapper<Audit> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Audit> buildQueryWrapper(AuditBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Audit> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getType()), Audit::getType, bo.getType());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), Audit::getStatus, bo.getStatus());
        lqw.like(StrUtil.isNotBlank(bo.getAlipay()), Audit::getAlipay, bo.getAlipay());
        lqw.eq(ObjectUtil.equal(LoginHelper.getUserType().getUserType(), UserType.XCX_USER.getUserType()), Audit::getCreateBy, LoginHelper.getUserId());
        lqw.orderByDesc(Audit::getCreateTime);
        return lqw;
    }

    /**
     * 新增提现审核
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(AuditBo bo) {
        Audit add = MapstructUtils.convert(bo, Audit.class);
        validEntityBeforeSave(add);
//        add.setAlipay(userService.getById(LoginHelper.getUserId()).getNickName());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setAuditId(add.getAuditId());
        }
        //减少金额
        userFlowingService.addAmount(LoginHelper.getUserId(), NumberUtil.mul(bo.getBalance(), -1), BusinessConstants.FLOWING_TYPE_CASH,
            null, BusinessConstants.FLOWING_TYPE_AMOUNT);
        return flag;
    }

    /**
     * 修改提现审核
     */
    @Override
    public Boolean updateByBo(AuditBo bo) {
        Audit update = MapstructUtils.convert(bo, Audit.class);
//        validEntityBeforeSave(update);
        Audit audit = baseMapper.selectById(update.getAuditId());
        if (update.getStatus().equals("2")) {
            //拒绝,提现金额返还钱包
            userFlowingService.addAmount(audit.getCreateBy(), update.getBalance(), BusinessConstants.FLOWING_TYPE_CASH, null, BusinessConstants.FLOWING_TYPE_AMOUNT);
        } else if (update.getStatus().equals("1")) {
            //同意, 将指定比例转到复购余额
//            BigDecimal toRepurchase = new BigDecimal(configService.queryValueByKey("toRepurchase"));
//            userFlowingService.addAmount(audit.getCreateBy(), update.getBalance().multiply(toRepurchase), BusinessConstants.FLOWING_TYPE_TO_REPURCHASE,
//                null, BusinessConstants.FLOWING_TYPE_REPURCHASE_AMOUNT);
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Audit entity) {
        BigDecimal balance = entity.getBalance();
        BigDecimal withdraw = new BigDecimal(configService.queryValueByKey("withdraw"));
//        BigDecimal divide = balance.divide(withdraw);
//        //判断subtract是不是整数
//        boolean isInt = divide.stripTrailingZeros().scale() <= 0;
//        if (!isInt || balance.compareTo(withdraw) < 0) {
//            throw new ServiceException("提现金额必须为" + withdraw + "的倍数");
//        }
        if (balance.compareTo(withdraw) < 0) {
            throw new ServiceException("最低提现金额" + withdraw);
        }
    }

    /**
     * 批量删除提现审核
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {

        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 查询提现商家审核列表
     */
    @Override
    public TableDataInfo<AuditVo> myList(PageQuery pageQuery) {
        LambdaQueryWrapper<Audit> lqw = buildQueryWrapper(new AuditBo());
        lqw.eq(Audit::getCreateBy, LoginHelper.getUserId());
        Page<AuditVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }
}
